package com.luban.ziya.sync;

import org.openjdk.jol.info.ClassLayout;
import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

/**
 * Created By ziya
 * 2020/10/22
 */
public class UnsafeSync {

    static int i = 0;

    public static void main (String[] args) throws Exception {
        Object obj = new Object();

        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Unsafe unsafe = (Unsafe) field.get(null);

        Thread t1 = new Thread(() -> {
            unsafe.monitorEnter(obj);

            System.out.println("t1 monitorEnter");

            System.out.println(ClassLayout.parseInstance(obj).toPrintable());

            for (int j = 0; j < 10000; j++) {
                i++;
            }

            unsafe.monitorExit(obj);
        });

        Thread t2 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            unsafe.monitorEnter(obj);

            System.out.println("t2 monitorEnter");

            for (int j = 0; j < 10000; j++) {
                i++;
            }

            unsafe.monitorExit(obj);
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(i);


//        System.out.println(ClassLayout.parseInstance(obj).toPrintable());


        System.out.println("hello");
    }
}
